#' @TODO 从MsigDB数据库文件中，获取指定关键字段基因集
#' @title 从MsigDB数据库文件中，获取指定关键字段基因集
#' @param pattern 字段匹配字符串向量
#' @param gmtFilePath 文件路径，如果是`NULL`，默认使用数据中心 v7.5.1版本的基因集文件
#' @param CleanPathName 是否去掉`'HALLMARK_'`等字段
#' @export
#' @return 返回gene list
#' @author *WYK*
getMsigDBGeneLst <- \(pattern = c("hallmark",'kegg'), CleanPathName = F, gmtFilePath = NULL){
    # require(progress)

    # pb <- progress_bar$new(total = 100, width = 45, incomplete = " ")

    if (!exists(".geneset_list", envir = .GlobalEnv)) {
        if (is.null(gmtFilePath)) {
            gmt_dir <- "/Pub/Backups/Data_Center/GeneSet/MsigDB/v7.5.1/msigdb.v7.5.1.symbols.gmt"
        } else {
            gmt_dir <- gmtFilePath
        }

        f_tmp <- purrr::quietly(GSA::GSA.read.gmt)
        .geneset_list <<- suppressMessages(f_tmp(gmt_dir))[['result']]
    }

    if (any(map_lgl(pattern, ~ grepl(x = "^all$", pattern = .x, ignore.case = T)))) {
        pathway <- .geneset_list$genesets
        names(pathway) <- .geneset_list$geneset.names
    } else {
        pathway_index <- map(pattern, function(x) {
            # pb$tick()
            grep(pattern = x, .geneset_list$geneset.names, ignore.case = T)
        })

        pathway <- .geneset_list$genesets[unlist(pathway_index)]
        names(pathway) <- .geneset_list$geneset.names[unlist(pathway_index)]

        stringr::str_glue("通过当前字段检索到的通路数目：{length(pathway)}") %>% cat('\n')
    }

    if (isTRUE(CleanPathName)) {
        names(pathway) <- str_split(names(pathway), "_") %>%
            map(., function(x) {
                str_c(x[-1], collapse = " ")
            })
    }

    return(pathway)
}


getMsigDBGeneLst_v2 <- \(pattern = c("hallmark",'kegg'), CleanPathName = F, gmtFilePath = NULL){
    if (!exists(".geneset_list", envir = .GlobalEnv)) {
        if (is.null(gmtFilePath)) {
            gmt_dir <- "/Pub/Users/wangyk/GEO_Data_ZhangGX/msgidb_v202302/human/msigdb_v2023.2.Hs_json_files_to_download_locally/msigdb.v2023.2.Hs.json"
        } else {
            gmt_dir <- gmtFilePath
        }

        .geneset_list <<- jsonlite::fromJSON(gmt_dir) %>% purrr::map(~ .x[["geneSymbols"]])
    }

    if (any(map_lgl(pattern, ~ grepl(x = "^all$", pattern = .x, ignore.case = T)))) {
        pathway <- .geneset_list
    } else {
        pathway_index <- map(pattern, function(x) {
            # pb$tick()
            grep(pattern = x, names(.geneset_list), ignore.case = T)
        })

        pathway <- .geneset_list[unlist(pathway_index)]

        stringr::str_glue("通过当前字段检索到的通路数目：{length(pathway)}") %>% message()
    }

    if (isTRUE(CleanPathName)) {
        names(pathway) <- str_split(names(pathway), "_") %>%
            map(., function(x) {
                str_c(x[-1], collapse = " ")
            })
    }

    return(pathway)
}